package com.ghc.api;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.List;

public class CreateNoteData implements Watcher {

//    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    private static ZooKeeper zooKeeper;

    /**
     * 建立会话
     */
    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {

        /*
         客户端可以通过创建⼀个zk实例来连接zk服务器
         new Zookeeper(connectString,sesssionTimeOut,Wather)
         connectString: 连接地址：IP：端⼝
         sesssionTimeOut：会话超时时间：单位毫秒
         Wather：监听器(当特定事件触发监听时，zk会通过watcher通知到客户端)
         */
        zooKeeper = new ZooKeeper("127.0.0.1:2180", 5000, new CreateNoteData());
        System.out.println(zooKeeper.getState());
        //计数工具类， CountDownLacth： 不让main结束， 让线程处于等待阻塞状态
//        countDownLatch.await();
        Thread.sleep(Integer.MAX_VALUE);
//        System.out.println("客户端与服务端回话真正建立了");
    }

    public void process(WatchedEvent watchedEvent) {

        /*
            当子节点列表改变时， 服务器端会发生noteChildrenChange通知
            要重新获取子节点列表， 同时， 通知是一次性的
         */
        if (watchedEvent.getType() == Event.EventType.NodeChildrenChanged){
            try {
                getChildrens();
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //当连接创建了，服务端发送给客户端SyncConnected事件
        if(watchedEvent.getState() == Event.KeeperState.SyncConnected){
            //解除主程序CountDownLatch上的等待阻塞
            System.out.println("process方法执行了......");
//            countDownLatch.countDown();
            try {
                getNoteData();
                //获取子节点
                getChildrens();
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * path : 获取数据的路径
     * watch : 是否开启监听
     * stat : 节点状态信息
     * null: 表示获取最新版本的数据
     * zk.getData(path, watch, stat);
     */
    private void getNoteData() throws KeeperException, InterruptedException {
        byte[] data = zooKeeper.getData("/ghc-persistent", false, null);
        System.out.println(new String(data));
    }
    /*
    获取某个节点的子节点列表方法
     */
    public static void getChildrens() throws KeeperException, InterruptedException {
        /*
        path:路径
         watch:是否要启动监听，当⼦节点列表发⽣变化，会触发监听
         zooKeeper.getChildren(path, watch);
         */
        List<String> children = zooKeeper.getChildren("/ghc-persistent", true);
        System.out.println(children);
    }
}
